<template>
  <div id="body">
    <el-card id="tableCrad">
      <el-row slot="header" type="flex" align="center" class="clearfix">
        <span style="margin-right: 32px">单位管理</span>
        <div type="flex" v-for="item in pQuery" :key="item.parent">
          <span style="margin: auto 8px">/</span>
          <el-link @click="clickLevelPage($event)" :parent="item.parent">{{
            item.ptitle
          }}</el-link>
        </div>
      </el-row>
      <!-- 查询行开始 -->
      <el-row id="btnRow" type="flex" style="width: 100%">
        <el-col :span="20">
          <el-row type="flex">
            <el-tooltip content="单位编码" placement="top" effect="light">
              <el-input
                class="input"
                v-model="code"
                placeholder="请输入单位编码"
                clearable
                style="margin-right: 10px; width: 33%"
              ></el-input>
            </el-tooltip>
            <el-tooltip content="单位名称" placement="top" effect="light">
              <el-input
                class="input"
                v-model="title"
                placeholder="请输入单位名称"
                clearable
                style="margin-right: 10px; width: 33%"
              ></el-input>
            </el-tooltip>
            <el-tooltip content="单位状态" placement="top" effect="light">
              <el-select
                v-model="deleted"
                @change="getPages"
                placeholder="请选择单位状态"
                style="margin-right: 10px; width: 33%"
              >
                <el-option label="全部" :value="-1"></el-option>
                <el-option label="可用" :value="0"></el-option>
                <el-option label="禁用" :value="1"></el-option>
              </el-select>
            </el-tooltip>
            <el-button
              @click="getPages"
              icon="el-icon-search"
              circle
            ></el-button>
          </el-row>
        </el-col>
        <el-col :span="2" :offset="2">
          <el-row>
            <el-button
              @click="addOpen"
              type="primary"
              icon="el-icon-plus"
              circle
            ></el-button>
            <el-button
              @click="deleteBatch"
              type="danger"
              icon="el-icon-delete"
              circle
            ></el-button>
          </el-row>
        </el-col>
      </el-row>
      <!-- 查询行结束 -->
      <!-- 表格开始 -->
      <el-table
        ref="multipleTable"
        :data="tableData"
        style="width: 100%"
        :height="tableHeight"
      >
        <el-table-column type="selection"> </el-table-column>
        <el-table-column fixed prop="id" label="编号" width="80" v-if="false">
        </el-table-column>
        <el-table-column fixed prop="code" label="编码" width="80">
        </el-table-column>
        <el-table-column
          prop="title"
          label="名称"
          align="center"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          prop="intro"
          label="描述"
          align="center"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span>{{
              isStrEmpty(scope.row.intro) ? "无" : scope.row.intro
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="location"
          label="位置"
          align="center"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span>{{
              isStrEmpty(scope.row.location) ? "无" : scope.row.location
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="photos" label="图片" align="center" width="120">
          <template slot-scope="scope">
            <el-image
              style="width: 100px"
              :src="baseURL + scope.row.photos"
              :preview-src-list="[baseURL + scope.row.photos]"
              v-if="!isStrEmpty(scope.row.photos)"
            >
            </el-image>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="排序" align="center" width="60">
        </el-table-column>
        <el-table-column
          prop="deleted"
          label="单位状态"
          align="center"
          width="80"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.deleted === 0 ? 'success' : 'danger'"
              disable-transitions
              >{{ scope.row.deleted === 0 ? "可用" : "禁用" }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="140">
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="nextLevelPage(scope.row)"
              type="text"
              size="small"
            >
              下一级
            </el-button>
            <el-button
              @click.native.prevent="editOpen(scope.row)"
              type="text"
              size="small"
            >
              编辑
            </el-button>
            <el-button
              @click.native.prevent="deleteRow(scope.row)"
              type="text"
              style="color: red"
              size="small"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        id="pageDevice"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="paginationData.currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="paginationData.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="paginationData.total"
      >
      </el-pagination>
      <!-- 表格结束 -->
    </el-card>
    <!-- 编辑表单开始 -->
    <el-dialog
      title="编辑"
      :visible.sync="editDialogVisible"
      width="50%"
      :before-close="editClose"
      v-loading="loading"
    >
      <el-form ref="editForm" :rules="rules" :model="row">
        <el-row type="flex">
          <el-col :span="7" v-if="false">
            <el-form-item label="菜单编号" prop="id">
              <el-input v-model="row.id" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="菜单编码" prop="code">
              <el-input v-model="row.code" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col :span="8">
            <el-form-item label="单位名称" prop="title">
              <el-input v-model="row.title"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="1">
            <el-form-item label="单位位置" prop="location">
              <el-input v-model="row.location"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="排序（数大优先）" prop="priority">
              <el-input v-model="row.priority" type="number"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col>
            <el-upload
              class="upload-demo"
              drag
              :before-upload="beforePicUpload"
              accept="image/*"
              action
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将图片拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">只能上传图片文件</div>
            </el-upload>
            <el-tag
              v-if="file != null"
              closable
              :disable-transitions="false"
              @close="deleteSubmitFile"
              type="success"
            >
              {{ file.name }}
            </el-tag>
          </el-col>
          <el-col>
            <el-form-item label="父级单位" label-width="120px" prop="parent">
              <el-select v-model="row.parent" placeholder="请选择" filterable>
                <el-option
                  v-for="item in selectPNodeOptions"
                  :key="item.code.toString()"
                  :label="item.title"
                  :value="item.code.toString()"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="单位状态" label-width="120px" prop="deleted">
              <el-select v-model="row.deleted" placeholder="请选择">
                <el-option label="可用" :value="0"></el-option>
                <el-option label="禁用" :value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="描述内容" label-width="120px" prop="intro">
              <el-input
                type="textarea"
                v-model="row.intro"
                placeholder="请输入描述内容"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item style="text-align: right">
          <el-button type="danger" @click="editClose">取消</el-button>
          <el-button type="primary" @click="editConfirm">确认编辑</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 编辑表单结束 -->
    <!-- 新添表单开始 -->
    <el-dialog
      title="增加"
      :visible.sync="addDialogVisible"
      width="50%"
      :before-close="addClose"
      v-loading="loading"
    >
      <el-form ref="addForm" :rules="rules" :model="row">
        <el-row type="flex">
          <el-col :span="8">
            <el-form-item label="单位名称" prop="title">
              <el-input v-model="row.title"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="1">
            <el-form-item label="单位位置" prop="location">
              <el-input v-model="row.location"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="排序（数大优先）" prop="priority">
              <el-input v-model="row.priority" type="number"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col>
            <el-upload
              class="upload-demo"
              drag
              :before-upload="beforePicUpload"
              accept="image/*"
              action
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将图片拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">只能上传图片文件</div>
            </el-upload>
            <el-tag
              v-if="file != null"
              closable
              :disable-transitions="false"
              @close="deleteSubmitFile"
              type="success"
            >
              {{ file.name }}
            </el-tag>
          </el-col>
          <el-col>
            <el-form-item label="父级单位" label-width="120px" prop="parent" >
              <el-select v-model="row.parent" placeholder="请选择" filterable>
                <el-option
                  v-for="item in selectPNodeOptions"
                  :key="item.code"
                  :label="item.title"
                  :value="item.code"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="单位状态" label-width="120px" prop="deleted">
              <el-select v-model="row.deleted" placeholder="请选择">
                <el-option label="可用" :value="0"></el-option>
                <el-option label="禁用" :value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="描述内容" label-width="120px" prop="intro">
              <el-input
                type="textarea"
                v-model="row.intro"
                placeholder="请输入描述内容"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item style="text-align: right">
          <el-button type="danger" @click="addClose">取消</el-button>
          <el-button type="primary" @click="addConfirm">立即增加</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 新添表单结束 -->
  </div>
</template>

<script>
import { isStrEmpty } from "@/utils/util";
import { baseURL } from "@/api/request";
export default {
  data() {
    return {
      baseURL: baseURL,
      //表格高度
      tableHeight: window.innerHeight - 320,
      //分页参数
      tableData: [],
      paginationData: {
        pageSize: 10,
        currentPage: 1,
        total: 50,
      },
      //查询参数
      pQuery: [],
      title: "",
      code: "",
      deleted: "",
      selectPNodeOptions: [],
      //修改或增加用到的的数据
      row: {},
      file: null,
      editDialogVisible: false,
      addDialogVisible: false,
      loading: false,
      rules: {
        title: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
        priority: [
          { required: true, message: "请输入排序数字", trigger: "blur" },
        ],
        deleted: [
          { required: true, message: "请选择单位状态", trigger: "change" },
        ],
        parent: [
          { required: true, message: "请选择父级单位", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    handleSizeChange(val) {
      this.paginationData.pageSize = val;
      this.getPages();
    },
    handleCurrentChange(val) {
      this.paginationData.currentPage = val;
      this.getPages();
    },
    getPages() {
      //axios请求方式，通过this.request使用分装好的axios实例
      this.request
        .get("/ent/getPage", {
          params: {
            title: this.title,
            code: this.code,
            deleted: this.deleted,
            currentPage: this.paginationData.currentPage,
            pageSize: this.paginationData.pageSize,
            parent: this.pQuery[this.pQuery.length - 1].parent,
          },
        })
        .then((res) => {
          if (res.code == 200) {
            this.tableData = res.data.records;
            this.paginationData.total = res.data.total;
            this.paginationData.currentPage = res.data.current;
            this.paginationData.pageSize = res.data.size;
          } else if (res.code == 204) {
            this.tableData = []; // 清空表格数据
            this.paginationData.total = 0; // 总记录数置为0
            this.paginationData.currentPage = 1; // 当前页置为第一页
            this.paginationData.pageSize = 10; // 每页大小置为默认值
          } else {
            this.pQuery.pop();
            this.$message({
              message: res.msg,
              type: "error",
            });
          }
        });
    },
    editOpen(row) {
      this.row = {
        id: row.id,
        code: row.code,
        parent: row.parent,
        title: row.title,
        intro: row.intro,
        location: row.location,
        photos: row.photos,
        priority: row.priority,
        deleted: row.deleted,
      };
      this.editDialogVisible = true;
    },
    editClose() {
      this.$refs["editForm"].resetFields();
      this.resetRowParam();
      this.editDialogVisible = false;
      this.file = null;
    },
    editConfirm() {
      this.$refs["editForm"].validate((valid) => {
        if (valid) {
          this.$alert("是否确定编辑", "提示", {
            confirmButtonText: "确定",
            callback: (action) => {
              const formData = new FormData();
              formData.append("file", this.file);
              formData.append("id", this.row.id);
              formData.append("code", this.row.code);
              formData.append("parent", this.row.parent);
              formData.append("title", this.row.title);
              formData.append("intro", this.row.intro);
              formData.append("location", this.row.location);
              formData.append("photos", this.row.photos);
              formData.append("priority", this.row.priority);
              formData.append("deleted", this.row.deleted);
              if (action == "confirm") {
                this.loading = true;
                this.request
                  .post("/ent/update", formData)
                  .then((res) => {
                    if (res.code == 200) {
                      this.$message({
                        message: res.msg,
                        type: "success",
                      });
                      this.editClose();
                      this.getPages();
                      this.getEntOptions();
                    } else {
                      this.$message({
                        message: res.msg,
                        type: "error",
                      });
                    }
                    this.loading = false;
                  })
                  .catch((err) => {
                    this.loading = false;
                  });
              }
            },
          });
        } else {
          this.$message({
            message: "请先规范填写表单信息",
            type: "warning",
          });
        }
      });
    },
    addOpen() {
      this.resetRowParam();
      this.addDialogVisible = true;
    },
    addClose() {
      this.$refs["addForm"].resetFields();
      this.resetRowParam();
      this.addDialogVisible = false;
      this.file = null;
    },
    addConfirm() {
      //if (this.file == null) {
      //  this.$message({
      //    message: "请先上传图片",
      //    type: "warning",
      //  });
      //  return;
      //}
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          this.$alert("是否确定新增", "提示", {
            confirmButtonText: "确定",
            callback: (action) => {
              if (action == "confirm") {
                const formData = new FormData();
                formData.append("file", this.file);
                formData.append("parent", this.row.parent);
                formData.append("title", this.row.title);
                formData.append("intro", this.row.intro);
                formData.append("location", this.row.location);
                formData.append("photos", this.row.photos);
                formData.append("priority", this.row.priority);
                formData.append("deleted", this.row.deleted);
                this.loading = true;
                this.request
                  .post("/ent/add", formData)
                  .then((res) => {
                    if (res.code == 200) {
                      this.$message({
                        message: res.msg,
                        type: "success",
                      });
                      this.addClose();
                      this.getPages();
                      this.getEntOptions();
                    } else {
                      this.$message({
                        message: res.msg,
                        type: "error",
                      });
                    }
                    this.loading = false;
                  })
                  .catch((err) => {
                    this.loading = false;
                  });
              }
            },
          });
        } else {
          this.$message({
            message: "请先规范填写表单信息",
            type: "warning",
          });
        }
      });
    },
    deleteRow(row) {
      this.$alert("是否确定删除", "提示", {
        confirmButtonText: "确定",
        callback: (action) => {
          if (action == "confirm") {
            this.request
              .post("/ent/delete", {
                id: row.id,
              })
              .then((res) => {
                if (res.code == 200) {
                  this.$message({
                    message: res.msg,
                    type: "success",
                  });
                  this.getPages();
                  this.getEntOptions();
                } else {
                  this.$message({
                    message: res.msg,
                    type: "error",
                  });
                }
              });
          }
        },
      });
    },
    deleteBatch() {
      var selectedList = this.$refs.multipleTable.selection;
      if (selectedList.length <= 0) {
        this.$message({
          message: "请选择至少一条数据",
          type: "warning",
        });
        return;
      }
      var ids = [];
      for (var i = 0; i < selectedList.length; i++) {
        ids.push(selectedList[i].id);
      }
      this.$alert("是否确定删除", "提示", {
        confirmButtonText: "确定",
        callback: (action) => {
          if (action == "confirm") {
            this.request
              .post("/ent/deleteBatch", {
                ids: JSON.stringify(ids),
              })
              .then((res) => {
                if (res.code == 200) {
                  this.$message({
                    message: res.msg,
                    type: "success",
                  });
                  this.getPages();
                  this.getEntOptions();
                } else {
                  this.$message({
                    message: res.msg,
                    type: "error",
                  });
                }
              });
          }
        },
      });
    },
    beforePicUpload(file) {
      this.file = file;
      return false;
    },
    deleteSubmitFile() {
      this.file = null;
    },
    getEntOptions() {
      this.request
        .get("/ent/getIndentOptions", {
          params: {
            parent: "-1",
            deleted: -1,
          },
        })
        .then((res) => {
          if (res.code == 200) {
            this.selectPNodeOptions = res.data;
          } else {
            this.$message({
              message: res.msg,
              type: "error",
            });
          }
        });
    },
    clickLevelPage(e) {
      for (var i = this.pQuery.length - 1; i >= 0; i--) {
        if (
          this.pQuery[i].parent ==
          e.currentTarget.getAttribute("parent").toString()
        )
          break;
        this.pQuery.pop(i);
      }
      this.getPages();
    },
    nextLevelPage(row) {
      var pNode = {
        parent: row.code,
        ptitle: row.title,
      };
      this.pQuery.push(pNode);
      this.getPages();
    },
    isStrEmpty(str) {
      return isStrEmpty(str);
    },
    resetRowParam() {
      this.row = {
        id: '',
        code: '',
        parent: '',
        title: '',
        intro: '',
        location: '',
        photos: '',
        priority: '',
        deleted: '',
      };
    }
  },
  mounted() {
    window.addEventListener("resize", () => {
      this.tableHeight = window.innerHeight - 320;
    });
  },
  created() {
    //创建
    //初始化面包屑
    var pRoot = {
      parent: "-1",
      ptitle: "根节点",
    };
    this.pQuery.push(pRoot);
    //初始化方法
    this.getPages();
    this.getEntOptions();
  },
};
</script>

<style scoped>
#body {
  display: flex;
  flex-direction: column;
  align-items: center;
}
#tableCrad {
  width: 100%;
}
#btnRow {
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}
#pageDevice {
  text-align: right;
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
</style>